<template>
  <div>
    <!-- 顶部面包屑标识与导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 后台管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/admin/product/goods' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: './' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>发布商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 添加数据的表单 -->
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="商品类别" prop="categoryId">
        <el-cascader
            clearable
            style="width: 100%;"
            placeholder="请选择商品类别"
            v-model="ruleForm.categoryId"
            :options="categoryOptions"></el-cascader>
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="ruleForm.goodsName"></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="goodsPrice">
        <el-input v-model="ruleForm.goodsPrice"></el-input>
      </el-form-item>
      <el-form-item label="商品库存" prop="goodsNumber">
        <el-input v-model="ruleForm.goodsNumber"></el-input>
      </el-form-item>

      <el-form-item label="商品信息">
        <div id="wangEditor"></div>
      </el-form-item>
      <el-form-item label="商品图像" prop="goodsLogo">
        <el-input v-model="ruleForm.goodsLogo"></el-input>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-switch
            v-model="ruleForm.goodsStatus"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#999">
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">发布</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="warning" @click="gotoList">返回列表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 父级类别的下拉菜单的选项数据
      categoryOptions: [],
      // 表单
      ruleForm: {
        categoryId: [],
        goodsName: '',
        goodsPrice: '',
        goodsInfo: '',
        goodsLogo: '',
        goodsNumber: '',
        goodsStatus: 0
      },
      // 表单规则
      rules: {
        categoryId: [
          {required: true, message: '请选择商品类别', trigger: 'change'}
        ],

        goodsName: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 2, max: 150, message: '长度在 2 到 150 个字符', trigger: 'blur'}
        ],

        goodsPrice: [
          {required: true, message: '请输入售价', trigger: 'blur'}
        ],
        goodsLogo: [
          {required: true, message: '请输入图标图片的URL', trigger: 'blur'},
          {min: 20, max: 200, message: '图标图片的URL长度必须在 20 到 200 个字符', trigger: 'blur'}
        ]

      },
      // 富文本编辑器
      editor: {}
    };
  },
  methods: {
    // 返回列表
    gotoList() {
      this.$router.push('/admin/content/goods');
    },
    // 初始化富文本编辑器
    initWangEditor() {
      this.editor = new this.wangEditor('#wangEditor');
      this.editor.config.uploadImgServer = 'http://localhost:9080/resources/upload/image/goods';
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadImgHooks = {
        customInsert: function(insertImgFn, result) {
          insertImgFn(result.data.url);
        }
      }
      this.editor.config.zIndex = 1;
      this.editor.create();
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9080/content/goods/add-new';
          console.log('url = ' + url);

          if (Array.isArray(this.ruleForm.categoryId)) {
            this.ruleForm.categoryId = this.ruleForm.categoryId[this.ruleForm.categoryId.length - 1];
          }

          this.ruleForm.detail = this.editor.txt.html();
          let formData = this.qs.stringify(this.ruleForm);
          console.log('formData = ' + formData);

          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
              .post(url, formData).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              let message = '发布商品成功！';
              this.$alert(message, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.resetForm(formName);
                  this.editor.txt.clear();
                }
              });
            } else {
              let title = '操作失败';
              this.$alert(jsonResult.message, title, {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          }).catch(error => {
            let title = '错误';
            let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
            this.$alert(message, title, {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
            console.log(error);
          });
        } else {
          console.log('请求参数格式错误！');
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 加载类别树的数据
    loadCategoryTree() {
      let url = 'http://localhost:9080/content/categories/tree';
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.categoryOptions = jsonResult.data;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    }
  },
  mounted() {
    this.loadCategoryTree();
    this.initWangEditor();
  }
}
</script>